package com.max.back.pharmacy.api;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.max.back.common.http.ResponseResult;
import com.max.back.entity.Drug;
import com.max.back.entity.Prescription;
import com.max.back.entity.PrescriptionItem;
import com.max.back.pharmacy.form.*;
import com.max.back.pharmacy.service.DrugService;
import com.max.back.pharmacy.service.PrescriptionItemService;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.max.back.pharmacy.service.PrescriptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/pharmacy")
public class PharmacyController {
  @Autowired private DrugService drugService;

  @Autowired private PrescriptionItemService prescriptionItemService;

  @Autowired private PrescriptionService prescriptionService;
  //    1.返回所有药品信息
  @RequestMapping("/getDrugList")
  public ResponseResult getDrugList(@RequestBody(required = false) DrugSearchForm drugSearchForm) {
    LambdaQueryWrapper<Drug> lqw = new LambdaQueryWrapper<>();
    lqw.eq(Drug::getDeleted, false);
    if (drugSearchForm!=null&&drugSearchForm.getName() != null && !drugSearchForm.getName().isEmpty())
      lqw.like(Drug::getName, drugSearchForm.getName());
    if (drugSearchForm!=null&&drugSearchForm.getDrugType() != null&&drugSearchForm.getDrugType()!=0)
      lqw.eq(Drug::getDrugType, drugSearchForm.getDrugType());
    List<Drug> list = this.drugService.list(lqw);
    if (list.size() == 0) {
      return ResponseResult.getSuccessResult(list, "药品列表为空！", null);
    }
    return ResponseResult.getSuccessResult(list,"获取药品列表成功！",null);
  }
  //    2.新建药品
  @PostMapping("/addDrug")
  public ResponseResult addDrug(@RequestBody @Validated DrugForm drugForm) {
    Drug drug =
        new Drug(
            IdUtil.simpleUUID(),
            drugForm.getName(),
            drugForm.getSpecification(),
            drugForm.getManufacturer(),
            drugForm.getUsageDosage(),
            drugForm.getUnit(),
            drugForm.getPrice(),
            drugForm.getDrugType(),
            drugForm.getInventory());
    boolean flag = this.drugService.save(drug);
    if (flag) {
      return ResponseResult.getMessageResult(null, "新建药品成功！");
    } else {
      return ResponseResult.getErrorResult("新建药品失败，请仔细检查字段！");
    }
  }
  //    3.修改药品信息
  @PostMapping("/updateDrug")
  public ResponseResult updateDrug(@RequestBody @Validated DrugForm drugForm) {
    Drug drug = this.drugService.getById(drugForm.getId());
    if (drug == null || drug.getDeleted()) {
      return ResponseResult.getErrorResult("要修改的药品信息不存在!");
    }
    drug.setName(drugForm.getName());
    drug.setInventory(drugForm.getInventory());
    drug.setPrice(drugForm.getPrice());
    drug.setUsageDosage(drugForm.getUsageDosage());
    drug.setSpecification(drugForm.getSpecification());
    drug.setManufacturer(drugForm.getManufacturer());
    drug.setGmtModify(new Date());
    boolean flag = this.drugService.updateById(drug);
    if (flag) return ResponseResult.getMessageResult(null, "修改药品信息成功！");
    return ResponseResult.getErrorResult("修改药品信息失败！");
  }
  //    4.删除药品
  @GetMapping("/deleteDrug")
  public ResponseResult deleteDrug(@RequestParam String id) {
    Drug drug = this.drugService.getById(id);
    if (drug == null || drug.getDeleted()) {
      return ResponseResult.getErrorResult("要删除的药品信息不存在!");
    }
    drug.setDeleted(true);
    drug.setGmtModify(new Date());
    if (this.drugService.updateById(drug))
      return ResponseResult.getMessageResult(null, "删除药品信息成功！");
    return ResponseResult.getErrorResult("删除药品信息失败！");
  }
  //    5.根据病历号或处方号获取患者的处方明细大对象列表
  @PostMapping("/getPrescriptionItemFormList")
  public ResponseResult getPrescriptionItemFormList(
      @RequestBody @Validated DispensingForm dispensingForm) {
    List<PrescriptionItemForm> list = new ArrayList<>();
    LambdaQueryWrapper<Prescription> lqw = new LambdaQueryWrapper<>();
    // 如果直接有处方id，直接查询
    if (!dispensingForm.getPrescriptionId().isEmpty()
        && dispensingForm.getPrescriptionId() != null) {
      list =
          this.prescriptionItemService.listPrescriptionItemForm(dispensingForm.getPrescriptionId());
    } else if (!dispensingForm.getPatientHistoryId().isEmpty()
        && dispensingForm.getPatientHistoryId() != null) {
      // 如果没有处方id，有病历id，先通过病历id查到处方，再用处方id查
      lqw.eq(Prescription::getPatientHistoryId, dispensingForm.getPatientHistoryId());
      Prescription prescription = this.prescriptionService.getOne(lqw);
      list = this.prescriptionItemService.listPrescriptionItemForm(prescription.getId());
    }
    if (list.size() == 0) {
      return ResponseResult.getSuccessResult(list, "发药列表为空！", null);
    }

    return ResponseResult.getSuccessResult(list, "获取处方明细大对象列表成功！", null);
  }
  //    6.批量发药

  @PostMapping("/dispenseDrug")
  public ResponseResult dispenseDrug(
      @RequestBody @Validated DispensingListForm dispensingListForm) {
    for (PrescriptionItemForm e : dispensingListForm.getPrescriptionItemForms()) {
      if (e.getPayStatus() == 2002 && e.getDeliveryStatus() == 3001) {
        PrescriptionItem prescriptionItem = this.prescriptionItemService.getById(e.getId());
        if (prescriptionItem == null || prescriptionItem.getDeleted())
          return ResponseResult.getErrorResult("至少存在已删除的处方项目:" + e.getName());
        prescriptionItem.setDeliveryStatus(3002);
        prescriptionItem.setGmtModify(new Date());
        if (!this.prescriptionItemService.updateById(prescriptionItem))
          return ResponseResult.getErrorResult("发药失败！");
      } else if (e.getPayStatus() == 2001)
        return ResponseResult.getErrorResult("至少存在未缴费的处方项目:" + e.getName());
      else if (e.getDeliveryStatus() == 3002) {
        return ResponseResult.getErrorResult("至少存在已发放的处方项目:" + e.getName());
      } else return ResponseResult.getErrorResult("至少发药失败的处方项目:" + e.getName());
    }
    return ResponseResult.getMessageResult(null, "发药成功！请将药品准确无误地交付给患者。");
  }
  //    7.根据病历号或处方号获取患者的处方明细大对象列表
  @PostMapping("/getRepercussionList")
  public ResponseResult getRepercussionList(@RequestBody @Validated DispensingForm dispensingForm) {
    List<PrescriptionItemForm> list = new ArrayList<>();
    LambdaQueryWrapper<Prescription> lqw = new LambdaQueryWrapper<>();
    // 如果直接有处方id，直接查询
    if (!dispensingForm.getPrescriptionId().isEmpty()
        && dispensingForm.getPrescriptionId() != null) {
      list = this.prescriptionItemService.listRepercussion(dispensingForm.getPrescriptionId());
    } else if (!dispensingForm.getPatientHistoryId().isEmpty()
        && dispensingForm.getPatientHistoryId() != null) {
      // 如果没有处方id，有病历id，先通过病历id查到处方，再用处方id查
      lqw.eq(Prescription::getPatientHistoryId, dispensingForm.getPatientHistoryId());
      Prescription prescription = this.prescriptionService.getOne(lqw);
      list = this.prescriptionItemService.listRepercussion(prescription.getId());
    }
    if (list.size() == 0) {
      return ResponseResult.getSuccessResult(list, "退药列表为空！", null);
    }

    return ResponseResult.getSuccessResult(list, "获取处方明细大对象列表成功！", null);
  }
  //    8.单个退药
  @GetMapping("/repercussionDrug")
  public ResponseResult repercussionDrug(@RequestParam String id) {
    PrescriptionItem prescriptionItem = this.prescriptionItemService.getById(id);
    if (prescriptionItem == null || prescriptionItem.getDeleted())
      return ResponseResult.getErrorResult("要退药的处方明细不存在！");
    else if (prescriptionItem.getDeliveryStatus() != 3002) {
      return ResponseResult.getErrorResult("发放状态不匹配：" + prescriptionItem.getDeliveryStatus());
    }
    prescriptionItem.setDeliveryStatus(3003);
    prescriptionItem.setGmtModify(new Date());
    if (this.prescriptionItemService.updateById(prescriptionItem))
      return ResponseResult.getMessageResult(null, "退药成功！请确保药品准确无误入库。");
    return ResponseResult.getErrorResult("退药失败！");
  }


}
